let http = require("http");
let events = require('events');
let Routes = require('./Route');

// 创建 eventEmitter 对象
let eventEmitter = new events.EventEmitter();

//循环绑定url的事件
Routes.forEach(route => {
    eventEmitter.on(route.path, (request, response) => {
        if (route.path === request.url && route.method === request.method) {
            let controller = require("./controller/" + route.controller);
            let f = Reflect.get(controller, route.function);
            console.log(f);
            if (typeof f === "function") {
                f(request, response);
            }
        }
    })
})

// 启动服务
http.createServer((request, response) => {
    console.log(request.url);

    // 分发
    if (eventEmitter.listenerCount(request.url) > 0) {
        eventEmitter.emit(request.url, request, response);
    } else {
        eventEmitter.emit('404', request.method, request.url, response);
    }

}).listen(8888);

console.log('Server running at http://127.0.0.1:8888/');
